package com.cskaoyan.controller.wx.storage;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.po.MarketStorage;
import com.cskaoyan.bean.storage.StorageVo;
import com.cskaoyan.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: 蒋镇泽
 * @Description:
 * @Date: 2022-06-07-21:08
 */
@RestController
@RequestMapping("wx/storage")
public class WXStorageUploadController {
    /* {"errno":0,"data":{"id":946,"key":"c18pj1e82emdqx37zv1p.png",
     "name":"111.png","type":"image/png","size":178697,
     "url":"http://182.92.235.201:8083/wx/storage/fetch/c18pj1e82emdqx37zv1p.png",
     "addTime":"2022-06-05 14:44:27","updateTime":"2022-06-05 14:44:27"},"errmsg":"成功"}*/
    @Autowired
    StorageService storageService;

    @PostMapping("upload")
    public BaseRespVo uploadFile(MultipartFile file) throws IOException {
        //正文类型
        String contentType = file.getContentType();
        if(!contentType.startsWith("image")){
            return BaseRespVo.invalidParameter("上传的不是图片");
        }

        MarketStorage storage = new MarketStorage();
        storage.setType(contentType);

        String originalFilename = file.getOriginalFilename();
        storage.setName(originalFilename);

        long size = file.getSize();
        storage.setSize((long) size);

        Date date = new Date();
        storage.setAddTime(date);
        storage.setUpdateTime(date);

        String suffix=null;
        if(originalFilename!=null){
            suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        String key = UUID.randomUUID().toString();
        storage.setKey(key+suffix);


        String basePath="D:\\mall2\\static";
        File filePath = new File(basePath, key + suffix);
        if(!filePath.getParentFile().exists()){
            boolean mkdir = filePath.getParentFile().mkdir();
        }
        //接受文件存入指定位置
        file.transferTo(filePath);

        String netPath="http://localhost:8083/admin/storage/";
        storage.setUrl(netPath+key+suffix);

        storageService.storageCreate(storage);
        StorageVo storageVo= new StorageVo(storage.getId(), storage.getKey(), storage.getName(), storage.getType(), Math.toIntExact(size), storage.getUrl(), storage.getAddTime(), storage.getUpdateTime());

        return BaseRespVo.ok(storageVo);



    }
}
